package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.ActivityModel;
import biznussoft.metercor.entity.NewInventoryModel;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ServiceOrderActivityDetailsFragment extends Fragment{

	
	private ScrollView svActivityEditScrollview,svActivityDisplayScrollview;
	private TextView tvStep,tvActivityname,tvstatus,tvPriority;
	private EditText etStep,etActivityname;
	private CheckBox cbBillable,etBillable;
	private ActivityModel model;
	private Spinner spStatus,spPriority;
	private RestClient client;
	public static ArrayList<NewInventoryModel> itemIdDetails;
	public static ArrayList<NewInventoryModel> technicainsList;
	private ImageView save;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		
		client =  MainActivity.mActivity.client;
		save = (ImageView) getView().findViewById(R.id.Submit);
		save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				updateAccount(model.getId());
				
			}
		});
		etStep = (EditText) getView().findViewById(R.id.etStep);
		etActivityname = (EditText) getView().findViewById(R.id.etActivityname);
		spStatus = (Spinner) getView().findViewById(R.id.spStatus);
		spPriority = (Spinner) getView().findViewById(R.id.spPriority);
		
		svActivityDisplayScrollview = (ScrollView) getView().findViewById(R.id.svActivitydisplayScrollview);
		svActivityEditScrollview = (ScrollView) getView().findViewById(R.id.svActivityEditScrollview);
		tvStep = (TextView) getView().findViewById(R.id.tvStep);
		tvActivityname = (TextView) getView().findViewById(R.id.tvActivityname);
		tvstatus = (TextView) getView().findViewById(R.id.tvStatus);
		tvPriority = (TextView) getView().findViewById(R.id.tvPriority);
		cbBillable = (CheckBox) getView().findViewById(R.id.tvBillable);
		etBillable = (CheckBox) getView().findViewById(R.id.etcbBillable);
		svActivityDisplayScrollview.setVisibility(View.VISIBLE);


		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.activity_details_fragment, null);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	@Override
	public void onPause() {
		setHasOptionsMenu(false);
		super.onPause();
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);


		MenuItem edit = menu.add("Edit");
		MenuItemCompat.setShowAsAction(edit, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		edit.setIcon(R.drawable.edit); 
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		
		if(item.getTitle().equals("Edit")){
			editActivity();
		}
		return super.onOptionsItemSelected(item);

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}


	


	

	

	

	public void editActivity(){
		svActivityDisplayScrollview.setVisibility(View.GONE);
		svActivityEditScrollview.setVisibility(View.VISIBLE);
		
		etStep.setText(model.getStep());
		etActivityname.setText(model.getActivityNameNew());
		
		if(model.isBillable()){
			etBillable.setChecked(true);
		}else{
			etBillable.setChecked(false);
		}
	}
	
	public void updateAccount(String id){               
		String objectType = "FConnect__Activitie__c";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Name",etStep.getText().toString());              
	/*	fields.put("FConnect__Planned_End_Date_Time__c",etendtime.getText().toString());
		fields.put("FConnect__Planned_Start_DateTime__c",etstarttime.getText().toString());*/
		fields.put("FConnect__Status__c", spStatus.getSelectedItem().toString());
		fields.put("FConnect__Priority__c",spPriority.getSelectedItem().toString());
		fields.put("FConnect__Billable__c",Boolean.toString(etBillable.isChecked()));
//		fields.put("FConnect__Activity__c",etActivityname.getText().toString());

		Log.i("TPT","Request is  :"+fields+" ::::::"+id); 
		try {

			RestRequest restRequest = RestRequest.getRequestForUpdate(getString(R.string.api_version),objectType,id,fields);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						Log.i("TPT","result is   :"+result);   
						getActivity().getSupportFragmentManager().beginTransaction().remove(ServiceOrderActivityDetailsFragment.this).commit();
						//finish();            
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}


	public void getWarehouseDetails(int Position){   

		model = ServiceOrderActivityRecordsFragment.list.get(Position);
		Session.sServiceOrderId = model.getSiteID(); 
		tvStep.setText(model.getStep());
		tvActivityname.setText(model.getActivityNameNew());
		tvstatus.setText(model.getStatus());
		cbBillable.setEnabled(false);
		cbBillable.setClickable(false);
		if(model.isBillable()){
			cbBillable.setChecked(true);
		}else{
			cbBillable.setChecked(false);
		}
		tvPriority.setText(model.getPriority());


		retriveItems();
		retriveTechnicians();


	}
	
	

	public void retriveItems(){

		try{  

			String accounts = "SELECT Name,Id,FConnect__Lot_ID__c,FConnect__Serial_ID__c FROM FConnect__Inventory__c where FConnect__Site__c="+"'"+Session.sTechnicianSiteId+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("NCS","Result is   :"+result.toString());

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						 itemIdDetails = new ArrayList<NewInventoryModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								NewInventoryModel bean = _gson.fromJson(jsonArray.getString(i), NewInventoryModel.class);
								itemIdDetails.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
	}
	public void retriveTechnicians(){

		try{  

			String accounts = "Select Id,name from FConnect__Group_Members__c";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("NCS","Result is   :"+result.toString());

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						technicainsList = new ArrayList<NewInventoryModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								NewInventoryModel bean = _gson.fromJson(jsonArray.getString(i), NewInventoryModel.class);
								technicainsList.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
	}

}
